package ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feign.product.SkuInfoFeignService;
import com.feign.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import ware.domain.WareSku;
import ware.service.WareSkuService;
import ware.mapper.WareSkuMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author panghu
 * @description 针对表【wms_ware_sku(商品库存)】的数据库操作Service实现
 * @createDate 2023-03-04 21:05:07
 */
@Service
public class WareSkuServiceImpl extends ServiceImpl<WareSkuMapper, WareSku>
        implements WareSkuService {

    @Autowired
    private SkuInfoFeignService skuInfoFeignService;

    @Override
    public Page<WareSku> querPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSku> queryWrapper = getQueryWrapper(params);
        Page<WareSku> wareInfoPage = new Page<>(Integer.parseInt((String) params.get("page")), Integer.parseInt((String) params.get("limit")));
        return this.baseMapper.selectPage(wareInfoPage, queryWrapper);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 不存在新增
        List<WareSku> wareSkus = this.baseMapper.selectList(new LambdaQueryWrapper<WareSku>().eq(WareSku::getSkuId, skuId).eq(WareSku::getWareId, wareId));
        if (ObjectUtils.isEmpty(wareSkus)) {
            WareSku wareSku = new WareSku();
            wareSku.setSkuId(skuId);
            wareSku.setStock(skuNum);
            wareSku.setStockLocked(0);
            // 远程设置sku的名字
            // todo 还有声明办法让异常不回滚呢
            try {
                R result = skuInfoFeignService.info(skuId);
                Map<String, Object> skuInfo = (Map<String, Object>) result.get("data");
                wareSku.setSkuName(skuInfo.get("skuName").toString());
            } catch (Exception ignored) {
                // 忽略异常，无需回滚
            }
            wareSku.setWareId(wareId);
            this.save(wareSku);
        } else {
            // 存在更新
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }


    private LambdaQueryWrapper<WareSku> getQueryWrapper(Map<String, Object> params) {
        LambdaQueryWrapper<WareSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(params.get("skuId")), WareSku::getSkuId, params.get("skuId"));
        wrapper.eq(!ObjectUtils.isEmpty(params.get("wareId")), WareSku::getSkuId, params.get("wareId"));
        return wrapper;
    }

}




